package com.shop2cn.iapi.sqmarketing.testcase;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.shop2cn.iapi.shenqisettlement.parameter.bean.AgentProductBean;
import com.shop2cn.iapi.sqmarketing.pojo.ActivityConditionItemPojo;
import com.shop2cn.iapi.sqoptrade.resp.Order;
import com.shop2cn.iapi.sqoptrade.resp.TradingServiceResp;
import com.ymatou.iapi.optrade.parameter.utill.Utils;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.SQPayGateWayCallService;
import com.ymttest.business.service.shenqi.DGSQBuildProxyChainCallService;
import com.ymttest.business.service.shenqi.SqTradingCallService;
import com.ymttest.business.service.shenqi.SqTradingMqService;
import com.ymttest.business.service.shenqi.SqmarketingService;
import com.ymttest.business.service.shenqi.bean.ShenqiUserSet;
import com.ymttest.database.model.sqmarketing.ActivityConditionItem;
import com.ymttest.database.model.sqmarketing.MarketingActivity;
import com.ymttest.database.model.sqmarketing.SendUserCoupon;
import com.ymttest.database.model.sqmarketing.UserJoinActivity;
import com.ymttest.database.sharding.db.ext.model.OrderDetailExtPo;
import com.ymttest.database.sharding.db.sharding.model.OrderDetailPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderWapper;
import com.ymttest.database.sqlwapper.sqmarketing.ActivityConditionItemWrapper;
import com.ymttest.database.sqlwapper.sqmarketing.MarketingActivityWrapper;
import com.ymttest.database.sqlwapper.sqmarketing.SendUserCouponWrapper;
import com.ymttest.database.sqlwapper.sqmarketing.UserJoinActivityWrapper;

public class Ts_SendCoupons {

	// java接口
	private static SendUserCouponWrapper sendUserCouponWrapper = new SendUserCouponWrapper();
	private static MarketingActivityWrapper marketingActivityWrapper = new MarketingActivityWrapper();
	private static ActivityConditionItemWrapper activityConditionItemWrapper = new ActivityConditionItemWrapper();
	private static UserJoinActivityWrapper userJoinActivityWrapper = new UserJoinActivityWrapper();

	private static OrderWapper orderWapper = new OrderWapper();

	private static long autotest_goodsOwnerId = ShenqiUserSet.autotest_goodsOwnerId;
	private static long cdfMembergoodsOwnerId = ShenqiUserSet.cdfMembergoodsOwnerId;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("满额送优惠券");
	}

	@Before
	public void caseUp() {
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult("http://sqmarketing.iapi.shop2cn.com/api/sqmarketingCallBack");
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private HashMap<String, BigDecimal> calConditionsPayableamount(
			List<OrderDetailPo> orderDetailPoList) {

		HashMap<String, BigDecimal> map = new HashMap<>();

		for (OrderDetailPo orderDetailPo : orderDetailPoList) {

			OrderDetailExtPo orderDetailExtPo = orderWapper
					.selectOrderDetailExtByOrderId(orderDetailPo
							.getOrderDetailId());

			BigDecimal payableAmount = orderDetailPo.getPayableAmount();
			String productId = orderDetailPo.getProductId();
			String thirdCategoryId = orderDetailPo.getThirdCategoryId()
					.toString();
			String brandId = orderDetailExtPo.getBrandId().toString();

			// 指定商品id总支付金额
			if (map.containsKey(productId))
				map.put(productId, map.get(productId).add(payableAmount));
			else
				map.put(productId, payableAmount);

			// 指定类目id总支付金额
			if (map.containsKey(thirdCategoryId))
				map.put(thirdCategoryId,
						map.get(thirdCategoryId).add(payableAmount));
			else
				map.put(thirdCategoryId, payableAmount);

			// 指定品牌id总支付金额
			if (map.containsKey(brandId))
				map.put(brandId, map.get(brandId).add(payableAmount));
			else
				map.put(brandId, payableAmount);
		}

		return map;
	}

	public void verifyDb(TradingServiceResp resp, int count, String currency) throws Exception {

		long mainOrderId = resp.getMainOrderId();
		long sellerId = resp.getOrderList().get(0).getSellerId();
		long userId = resp.getUserId();
		HashMap<String, BigDecimal> map = new HashMap<>();

		// 手动调用支付后送券接口
		SqmarketingService.sqmarketingCallBack(userId, mainOrderId);
		
		for (Order order : resp.getOrderList()) {
			
			map = this.calConditionsPayableamount(order.getOrderDetailPoList());
		}

		// 总支付金额
		map.put("totalPayablement", resp.getPayableAmount());

		List<MarketingActivity> marketingActivities = marketingActivityWrapper
				.selectActivitiesBySellerId(sellerId);

		// 指定商品活动 
		List<MarketingActivity> specifyProductIdActivities = marketingActivities
				.stream()
				.filter(activity -> activity.getCondition_type().compareTo(
						(byte) 1) == 0).collect(Collectors.toList());

		if (specifyProductIdActivities.size() > 0) {

			for (MarketingActivity marketingActivity : specifyProductIdActivities) {

				Long activityId = marketingActivity.getId();
				List<ActivityConditionItem> conditionItems = activityConditionItemWrapper
						.selectItemsByActivityId(activityId);

				for (ActivityConditionItem item : conditionItems) {

					if (map.containsKey(item.getActivit_condition_item())) {
						if (map.get(item.getActivit_condition_item())
								.compareTo(
										marketingActivity
												.getPay_amount_threshold()) >= 0
								&& count <= marketingActivity.getCount_limit()
								&& currency.equalsIgnoreCase(marketingActivity
										.getPay_currency())) {

							String[] coupons = marketingActivity
									.getCoupon_batch_ids().split(";");

							for (int i = 0; i < coupons.length; i++) {

								Logger.comment(String.format(
										"指定商品：%s，满足金额送券：%s",
										item.getActivit_condition_item(),
										coupons[i]));

								SendUserCoupon expected = new SendUserCoupon();

								expected.setActivity_id(marketingActivity
										.getId());
								expected.setCoupon_batch_id(coupons[i]);
								expected.setUser_id(userId);
								expected.setSeller_id(sellerId);

								this.verifySendUserCouponTable(mainOrderId,
										expected);
							}

							UserJoinActivity actualUserJoinActivity = userJoinActivityWrapper
									.selectByActivityIdAndUserId(
											marketingActivity.getId(), userId);

							Logger.verifyEquals(count,
									actualUserJoinActivity.getJoin_count(),
									"验证用户参与活动次数");
						}
					}
				}
			}
		}

		// 所有商品活动
		List<MarketingActivity> allProductIdActivities = marketingActivities
				.stream()
				.filter(activity -> activity.getCondition_type().compareTo(
						(byte) 2) == 0).collect(Collectors.toList());

		if (allProductIdActivities.size() > 0) {

			for (MarketingActivity marketingActivity : allProductIdActivities) {

				BigDecimal totalPayablement = map.get("totalPayablement");

				if (totalPayablement.compareTo(marketingActivity
						.getPay_amount_threshold()) >= 0
						&& count <= marketingActivity.getCount_limit()
						&& currency.equalsIgnoreCase(marketingActivity
								.getPay_currency())) {

					String[] coupons = marketingActivity.getCoupon_batch_ids()
							.split(";");

					for (int i = 0; i < coupons.length; i++) {

						Logger.comment(String.format("所有商品，满足金额送券：%s",
								coupons[i]));

						SendUserCoupon expected = new SendUserCoupon();

						expected.setActivity_id(marketingActivity.getId());
						expected.setCoupon_batch_id(coupons[i]);
						expected.setUser_id(userId);
						expected.setSeller_id(sellerId);

						this.verifySendUserCouponTable(mainOrderId, expected);
					}

					UserJoinActivity actualUserJoinActivity = userJoinActivityWrapper
							.selectByActivityIdAndUserId(
									marketingActivity.getId(), userId);

					Logger.verifyEquals(count,
							actualUserJoinActivity.getJoin_count(),
							"验证用户参与活动次数");
				}
			}
		}

		// 品类/分类活动
		List<MarketingActivity> brandIdOrCategoryIdActivities = marketingActivities
				.stream()
				.filter(activity -> activity.getCondition_type().compareTo(
						(byte) 3) == 0).collect(Collectors.toList());

		if (brandIdOrCategoryIdActivities.size() > 0) {

			for (MarketingActivity marketingActivity : brandIdOrCategoryIdActivities) {

				Long activityId = marketingActivity.getId();
				List<ActivityConditionItem> conditionItems = activityConditionItemWrapper
						.selectItemsByActivityId(activityId);

				for (ActivityConditionItem item : conditionItems) {

					if (map.containsKey(item.getActivit_condition_item())) {
						if (map.get(item.getActivit_condition_item())
								.compareTo(
										marketingActivity
												.getPay_amount_threshold()) >= 0
								&& count <= marketingActivity.getCount_limit()
								&& currency.equalsIgnoreCase(marketingActivity
										.getPay_currency())) {

							String[] coupons = marketingActivity
									.getCoupon_batch_ids().split(";");

							for (int i = 0; i < coupons.length; i++) {

								Logger.comment(String.format(
										"指定类目/品牌：%s，满足金额送券：%s",
										item.getActivit_condition_item(),
										coupons[i]));

								SendUserCoupon expected = new SendUserCoupon();

								expected.setActivity_id(marketingActivity
										.getId());
								expected.setCoupon_batch_id(coupons[i]);
								expected.setUser_id(userId);
								expected.setSeller_id(sellerId);

								this.verifySendUserCouponTable(mainOrderId,
										expected);
							}

							UserJoinActivity actualUserJoinActivity = userJoinActivityWrapper
									.selectByActivityIdAndUserId(
											marketingActivity.getId(), userId);

							Logger.verifyEquals(count,
									actualUserJoinActivity.getJoin_count(),
									"验证用户参与活动次数");
						}
					}
				}
			}
		}
	}

	public void verifySendUserCouponTable(long mainOrderId,
			SendUserCoupon expected) {

		SendUserCoupon actualSendUserCoupon = sendUserCouponWrapper
				.selectByMainOrderIdAndActivityIdAndCoupon(mainOrderId,
						expected.getActivity_id(),
						expected.getCoupon_batch_id());

		Logger.comment("验证send_user_coupon表");

		Logger.verifyEquals(expected.getSeller_id(),
				actualSendUserCoupon.getSeller_id(), "验证Seller_id");
		Logger.verifyEquals(expected.getUser_id(),
				actualSendUserCoupon.getUser_id(), "验证User_id");
		Logger.verifyEquals(expected.getCoupon_batch_id(),
				actualSendUserCoupon.getCoupon_batch_id(), "验证Coupon_batch_id");
		Logger.verifyEquals(expected.getActivity_id(),
				actualSendUserCoupon.getActivity_id(), "验证Activity_id");
		Logger.verifyEquals((byte) 1, actualSendUserCoupon.getSned_status(),
				"验证Sned_status");
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_001() {
		Logger.start(true, "新增营销活动，满足指定商品，超过指定金额，赠券成功");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder1(productBean, productBean.getSellerId());

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			SqTradingMqService.updateLiveOrder(false, orderId);

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(autotest_goodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件
			ActivityConditionItemPojo activityConditionItem = new ActivityConditionItemPojo();

			activityConditionItem.setConditionType(1);
			activityConditionItem.setItemList(Arrays.asList(placeOrderResp
					.getOrderList().get(0).getOrderDetailPoList().get(0)
					.getProductId()));

			// 创建满金额赠优惠活动
			SqmarketingService.saveOrUpdaateMarketingActivity(1,
					productBean.getCurrency(), BigDecimal.ONE,
					autotest_goodsOwnerId, 1,
					Arrays.asList(activityConditionItem));

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			this.verifyDb(placeOrderResp, 1,
					Utils.nullIsCNY(productBean.getCurrency()));

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_002() {
		Logger.start(true, "新增营销活动，所有商品，超过指定金额，赠券成功");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder1(productBean, productBean.getSellerId());

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			SqTradingMqService.updateLiveOrder(false, orderId);

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(autotest_goodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件
			ActivityConditionItemPojo activityConditionItem = new ActivityConditionItemPojo();

			activityConditionItem.setConditionType(1);
			activityConditionItem.setItemList(Arrays.asList(placeOrderResp
					.getOrderList().get(0).getOrderDetailPoList().get(0)
					.getProductId()));

			// 创建满金额赠优惠活动
			SqmarketingService.saveOrUpdaateMarketingActivity(2,
					productBean.getCurrency(), BigDecimal.ONE,
					autotest_goodsOwnerId, 1,
					Arrays.asList(activityConditionItem));

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			this.verifyDb(placeOrderResp, 1, Utils.nullIsCNY(productBean.getCurrency()));

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_003() {
		Logger.start(true, "新增营销活动，指定类目，超过指定金额，赠券成功");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder1(productBean, productBean.getSellerId());

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			SqTradingMqService.updateLiveOrder(false, orderId);

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(autotest_goodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件
			ActivityConditionItemPojo activityConditionItem = new ActivityConditionItemPojo();

			activityConditionItem.setConditionType(3);
			activityConditionItem.setItemList(Arrays.asList(placeOrderResp
					.getOrderList().get(0).getOrderDetailPoList().get(0)
					.getThirdCategoryId().toString()));

			// 创建满金额赠优惠活动
			SqmarketingService.saveOrUpdaateMarketingActivity(3,
					productBean.getCurrency(), BigDecimal.ONE,
					autotest_goodsOwnerId, 1,
					Arrays.asList(activityConditionItem));

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			this.verifyDb(placeOrderResp, 1, Utils.nullIsCNY(productBean.getCurrency()));

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_004() {
		Logger.start(true, "新增营销活动，所有商品，未超过指定金额，赠券失败");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder1(productBean, productBean.getSellerId());

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			SqTradingMqService.updateLiveOrder(false, orderId);

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(autotest_goodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件
			ActivityConditionItemPojo activityConditionItem = new ActivityConditionItemPojo();

			activityConditionItem.setConditionType(1);
			activityConditionItem.setItemList(Arrays.asList(placeOrderResp
					.getOrderList().get(0).getOrderDetailPoList().get(0)
					.getProductId()));

			// 创建满金额赠优惠活动
			SqmarketingService.saveOrUpdaateMarketingActivity(2, productBean
					.getCurrency(),
					placeOrderResp.getPayableAmount().add(BigDecimal.ONE),
					autotest_goodsOwnerId, 1, Arrays
							.asList(activityConditionItem));

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			this.verifyDb(placeOrderResp, 0, Utils.nullIsCNY(productBean.getCurrency()));

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_005() {
		Logger.start(true, "新增营销活动，多个商品，其中一个商品未超过指定金额，赠券成功");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) cdfMembergoodsOwnerId, 0, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeMultiComposeProductOrderWithIntegral(cdfMembergoodsOwnerId);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			SqTradingMqService.updateLiveOrder(false, orderId);

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(cdfMembergoodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件1
			ActivityConditionItemPojo activityConditionItem1 = new ActivityConditionItemPojo();

			activityConditionItem1.setConditionType(1);
			activityConditionItem1.setItemList(Arrays.asList(placeOrderResp
					.getOrderList().get(0).getOrderDetailPoList().get(0)
					.getProductId()));

			// 创建满金额赠优惠活动1
			SqmarketingService.saveOrUpdaateMarketingActivity(1,
					productBean.getCurrency(), BigDecimal.ONE,
					cdfMembergoodsOwnerId, 1,
					Arrays.asList(activityConditionItem1));

			// 创建满金额赠优惠条件2
			ActivityConditionItemPojo activityConditionItem2 = new ActivityConditionItemPojo();

			activityConditionItem2.setConditionType(1);
			activityConditionItem2.setItemList(Arrays.asList(placeOrderResp
					.getOrderList().get(0).getOrderDetailPoList().get(1)
					.getProductId()));

			// 创建满金额赠优惠活动2
			SqmarketingService.saveOrUpdaateMarketingActivity(1,
					productBean.getCurrency(), placeOrderResp.getOrderList()
							.get(0).getOrderDetailPoList().get(1)
							.getPayableAmount().add(BigDecimal.ONE),
					cdfMembergoodsOwnerId, 1,
					Arrays.asList(activityConditionItem2));

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			this.verifyDb(placeOrderResp, 1, Utils.nullIsCNY(productBean.getCurrency()));

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_006() {
		Logger.start(true, "新增营销活动，指定类目和品牌，超过指定金额，赠券成功");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) cdfMembergoodsOwnerId, 0, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeMultiComposeProductOrderWithIntegral(cdfMembergoodsOwnerId);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			SqTradingMqService.updateLiveOrder(false, orderId);

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(cdfMembergoodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件1
			ActivityConditionItemPojo activityConditionItem1 = new ActivityConditionItemPojo();

			activityConditionItem1.setConditionType(3);
			activityConditionItem1.setItemList(Arrays.asList(String
					.valueOf("1004")));

			// 创建满金额赠优惠条件2
			ActivityConditionItemPojo activityConditionItem2 = new ActivityConditionItemPojo();

			activityConditionItem2.setConditionType(2);
			activityConditionItem2.setItemList(Arrays.asList(String
					.valueOf("1234")));

			// 创建满金额赠优惠活动1
			SqmarketingService.saveOrUpdaateMarketingActivity(3, productBean
					.getCurrency(), BigDecimal.ONE, cdfMembergoodsOwnerId, 1,
					Arrays.asList(activityConditionItem1,
							activityConditionItem2));

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			this.verifyDb(placeOrderResp, 1, Utils.nullIsCNY(productBean.getCurrency()));

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_007() {
		Logger.start(true, "新增可赠送多次优惠券的营销活动，所有商品，超过指定金额，多次赠券成功");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(autotest_goodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件
			ActivityConditionItemPojo activityConditionItem = new ActivityConditionItemPojo();

			activityConditionItem.setConditionType(2);
			activityConditionItem.setItemList(Arrays.asList(""));

			// 创建满金额赠优惠活动
			SqmarketingService.saveOrUpdaateMarketingActivity(2, "CNY",
					BigDecimal.ONE, autotest_goodsOwnerId, 2,
					Arrays.asList(activityConditionItem));

			for (int i = 0; i < 2; i++) {

				AgentProductBean productBean = DGSQBuildProxyChainCallService
						.createProxychain((int) autotest_goodsOwnerId, 0, false);

				TradingServiceResp placeOrderResp = SqTradingCallService
						.placeOrder1(productBean, productBean.getSellerId());

				Long userId = placeOrderResp.getUserId();
				long orderId = placeOrderResp.getOrderList().get(0)
						.getOrderId();
				BigDecimal totalPrice = placeOrderResp.getPayableAmount();

				SqTradingMqService.updateLiveOrder(false, orderId);

				// 支付订单
				Long thirdTradingId = SqTradingCallService.payOrder(userId,
						placeOrderResp.getTradingId());

				// 支付网关支付回调交易
				SQPayGateWayCallService.DGSQNotifyCall(
						String.valueOf(thirdTradingId),
						totalPrice.subtract(BigDecimal.ZERO).toString(),
						userId.intValue(), BigDecimal.ZERO.toPlainString());

				TradingSyncService.getSyncResult(orderId);
				Thread.sleep(10000);

				Logger.comment("前置数据准备结束");

				this.verifyDb(placeOrderResp, i + 1, Utils.nullIsCNY(productBean.getCurrency()));
			}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_008() {
		Logger.start(true, "新增多个营销活动，一个支付单满足多个赠券活动，赠券成功");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) cdfMembergoodsOwnerId, 0, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeMultiComposeProductOrderWithIntegral(cdfMembergoodsOwnerId);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			SqTradingMqService.updateLiveOrder(false, orderId);

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(cdfMembergoodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件1
			ActivityConditionItemPojo activityConditionItem1 = new ActivityConditionItemPojo();

			activityConditionItem1.setConditionType(3);
			activityConditionItem1.setItemList(Arrays.asList(String
					.valueOf("1004")));

			// 创建满金额赠优惠条件2
			ActivityConditionItemPojo activityConditionItem2 = new ActivityConditionItemPojo();

			activityConditionItem2.setConditionType(2);
			activityConditionItem2.setItemList(Arrays.asList(String
					.valueOf("1234")));

			// 创建满金额赠优惠活动1
			SqmarketingService.saveOrUpdaateMarketingActivity(3, productBean
					.getCurrency(), BigDecimal.ONE, cdfMembergoodsOwnerId, 1,
					Arrays.asList(activityConditionItem1,
							activityConditionItem2));

			// 创建满金额赠优惠条件1
			ActivityConditionItemPojo activityConditionItem3 = new ActivityConditionItemPojo();

			activityConditionItem3.setConditionType(1);
			activityConditionItem3.setItemList(Arrays.asList(String
					.valueOf("all")));

			// 创建满金额赠优惠活动2
			SqmarketingService.saveOrUpdaateMarketingActivity(2,
					productBean.getCurrency(), BigDecimal.ONE,
					cdfMembergoodsOwnerId, 1,
					Arrays.asList(activityConditionItem3));

			// 创建满金额赠优惠条件1
			ActivityConditionItemPojo activityConditionItem4 = new ActivityConditionItemPojo();

			activityConditionItem4.setConditionType(3);
			activityConditionItem4.setItemList(Arrays.asList(String
					.valueOf("1003")));

			// 创建满金额赠优惠活动3
			SqmarketingService.saveOrUpdaateMarketingActivity(3,
					productBean.getCurrency(), BigDecimal.ONE,
					cdfMembergoodsOwnerId, 1,
					Arrays.asList(activityConditionItem4));

			// 创建满金额赠优惠条件1
			ActivityConditionItemPojo activityConditionItem5 = new ActivityConditionItemPojo();

			activityConditionItem5.setConditionType(1);
			activityConditionItem5.setItemList(Arrays.asList(String
					.valueOf("djgdkljgklf")));

			// 创建满金额赠优惠活动4
			SqmarketingService.saveOrUpdaateMarketingActivity(1,
					productBean.getCurrency(), BigDecimal.ONE,
					cdfMembergoodsOwnerId, 1,
					Arrays.asList(activityConditionItem5));

			// 创建满金额赠优惠条件1
			ActivityConditionItemPojo activityConditionItem6 = new ActivityConditionItemPojo();

			activityConditionItem6.setConditionType(1);
			activityConditionItem6.setItemList(Arrays.asList(placeOrderResp
					.getOrderList().get(0).getOrderDetailPoList().get(0)
					.getProductId()));

			// 创建满金额赠优惠活动5
			SqmarketingService.saveOrUpdaateMarketingActivity(1,
					productBean.getCurrency(), BigDecimal.ONE,
					cdfMembergoodsOwnerId, 1,
					Arrays.asList(activityConditionItem6));

			// 创建满金额赠优惠条件1
			ActivityConditionItemPojo activityConditionItem7 = new ActivityConditionItemPojo();

			activityConditionItem7.setConditionType(1);
			activityConditionItem7.setItemList(Arrays.asList(placeOrderResp
					.getOrderList().get(0).getOrderDetailPoList().get(0)
					.getProductId()));

			// 创建满金额赠优惠活动6
			SqmarketingService.saveOrUpdaateMarketingActivity(1, productBean
					.getCurrency(),
					placeOrderResp.getPayableAmount().add(BigDecimal.ONE),
					cdfMembergoodsOwnerId, 1, Arrays
							.asList(activityConditionItem7));

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			this.verifyDb(placeOrderResp, 1, Utils.nullIsCNY(productBean.getCurrency()));

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_009() {
		Logger.start(true, "新增多个活动，分别指定类目和品牌，其中类目超过指定金额，品牌未超过，赠券成功");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) cdfMembergoodsOwnerId, 0, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeMultiComposeProductOrderWithIntegral(cdfMembergoodsOwnerId);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			SqTradingMqService.updateLiveOrder(false, orderId);

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(cdfMembergoodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件1
			ActivityConditionItemPojo activityConditionItem1 = new ActivityConditionItemPojo();

			activityConditionItem1.setConditionType(3);
			activityConditionItem1.setItemList(Arrays.asList(String
					.valueOf("1003")));

			// 创建满金额赠优惠活动1
			SqmarketingService.saveOrUpdaateMarketingActivity(3,
					productBean.getCurrency(), BigDecimal.ONE,
					cdfMembergoodsOwnerId, 1,
					Arrays.asList(activityConditionItem1));

			// 创建满金额赠优惠条件2
			ActivityConditionItemPojo activityConditionItem2 = new ActivityConditionItemPojo();

			activityConditionItem2.setConditionType(2);
			activityConditionItem2.setItemList(Arrays.asList(String
					.valueOf("1234")));

			// 创建满金额赠优惠活动2
			SqmarketingService.saveOrUpdaateMarketingActivity(3,
					productBean.getCurrency(), totalPrice.add(BigDecimal.ONE),
					cdfMembergoodsOwnerId, 1,
					Arrays.asList(activityConditionItem2));

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			this.verifyDb(placeOrderResp, 1, Utils.nullIsCNY(productBean.getCurrency()));

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_010() {
		Logger.start(true, "新增营销活动，所有商品，超过赠券次数，赠券失败");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(autotest_goodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件
			ActivityConditionItemPojo activityConditionItem = new ActivityConditionItemPojo();

			activityConditionItem.setConditionType(2);
			activityConditionItem.setItemList(Arrays.asList(""));

			// 创建满金额赠优惠活动
			SqmarketingService.saveOrUpdaateMarketingActivity(2, "CNY",
					BigDecimal.ONE, autotest_goodsOwnerId, 1,
					Arrays.asList(activityConditionItem));

			for (int i = 0; i < 2; i++) {

				AgentProductBean productBean = DGSQBuildProxyChainCallService
						.createProxychain((int) autotest_goodsOwnerId, 0, false);

				TradingServiceResp placeOrderResp = SqTradingCallService
						.placeOrder1(productBean, productBean.getSellerId());

				Long userId = placeOrderResp.getUserId();
				long orderId = placeOrderResp.getOrderList().get(0)
						.getOrderId();
				BigDecimal totalPrice = placeOrderResp.getPayableAmount();

				SqTradingMqService.updateLiveOrder(false, orderId);

				// 支付订单
				Long thirdTradingId = SqTradingCallService.payOrder(userId,
						placeOrderResp.getTradingId());

				// 支付网关支付回调交易
				SQPayGateWayCallService.DGSQNotifyCall(
						String.valueOf(thirdTradingId),
						totalPrice.subtract(BigDecimal.ZERO).toString(),
						userId.intValue(), BigDecimal.ZERO.toPlainString());

				TradingSyncService.getSyncResult(orderId);
				Thread.sleep(10000);

				Logger.comment("前置数据准备结束");

				this.verifyDb(placeOrderResp, i + 1, Utils.nullIsCNY(productBean.getCurrency()));
			}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_011() {
		Logger.start(true, "新增营销活动包含多个批次，满足指定商品，超过指定金额，送多张券，赠券成功");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder1(productBean, productBean.getSellerId());

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			SqTradingMqService.updateLiveOrder(false, orderId);

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(autotest_goodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件
			ActivityConditionItemPojo activityConditionItem = new ActivityConditionItemPojo();

			activityConditionItem.setConditionType(1);
			activityConditionItem.setItemList(Arrays.asList(placeOrderResp
					.getOrderList().get(0).getOrderDetailPoList().get(0)
					.getProductId()));

			// 创建满金额赠优惠活动
			SqmarketingService.saveOrUpdaateMarketingActivityWithBatchs(1,
					productBean.getCurrency(), BigDecimal.ONE,
					autotest_goodsOwnerId, 1,
					Arrays.asList(activityConditionItem));

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			this.verifyDb(placeOrderResp, 1, Utils.nullIsCNY(productBean.getCurrency()));

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SendCoupons_012() {
		Logger.start(true, "新增营销活动，满足指定商品，超过指定金额，币种对应不上，赠券失败");

		try {

			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder1(productBean, autotest_goodsOwnerId);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			SqTradingMqService.updateLiveOrder(false, orderId);

			// 删除之前的营销活动，避免条件重复报错
			SqmarketingService
					.deleteAllMarketingActivity(autotest_goodsOwnerId);

			// 清除营销活动缓存
			SqmarketingService.deleteCache();

			// 创建满金额赠优惠条件
			ActivityConditionItemPojo activityConditionItem = new ActivityConditionItemPojo();

			activityConditionItem.setConditionType(1);
			activityConditionItem.setItemList(Arrays.asList(placeOrderResp
					.getOrderList().get(0).getOrderDetailPoList().get(0)
					.getProductId()));

			// 创建满金额赠优惠活动
			SqmarketingService.saveOrUpdaateMarketingActivity(1, "USD",
					BigDecimal.ONE, autotest_goodsOwnerId, 1,
					Arrays.asList(activityConditionItem));

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			this.verifyDb(placeOrderResp, 0, Utils.nullIsCNY(productBean.getCurrency()));

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}
